<template>
  <!-- CooperationList 合作管理 -->
  <PageContainer>
    <view class="container">
      <Header v-model="headerHeight" title="合作管理" :is-box-shadow="false" />

      <view class="headCard px-15 py-10">
        <view class="disFlx">
          <TImage
            :src="globalConfig?.logo"
            width="110rpx"
            height="110rpx"
            border-radius="10rpx"
            error-img-type="unit"
          />
          <view class="pl-15 py-2 fz-14 rightBox">
            <view>
              <view class="fz-16 fw-7 ov-1 pt-5">{{ globalConfig?.name }}</view>
              <view class="fz-12 pt-4 color3">{{ quotaData.product }}</view>
            </view>
            <view class="disFlxCC" @click="visible = true">
              <view class="ali-icon icon-erweima" style="font-size: 60rpx"></view>
              <view class="color3" style="font-size: 28rpx">合作码</view>
            </view>
          </view>
        </view>
        <view class="disFlxJS">
          <view>
            <view class="mt-15">
              <text>合作额度</text>
              <text class="pl-10">{{ quotaData.quota }}家</text>
            </view>
            <view class="mt-10 pb-5 disFlxJS">
              <view>
                <text>剩余额度</text>
                <text class="pl-10">{{ quotaData.usable }}家</text>
              </view>
              <view></view>
              <!-- <view class="color2" @click="goDescription">合作说明</view> -->
            </view>
          </view>
          <view class="shopBtn">
            <button class="share-btn" open-type="share" type="none" />
            <text>邀请开通</text>
          </view>
        </view>
      </view>

      <view class="stickyTabs" :style="'top:' + headerHeight + 'px; background-color: #f5f5f5;'">
        <view class="pb-8" style="border-radius: 20rpx 20rpx 0 0">
          <Tabs v-model="currentTab" :data="dataList">
            <TabNav tabBarColor="#2878FF" tabActiveFontSize="32rpx" />
            <TabsItem
              v-for="(item, index) in tabItemList"
              :key="index"
              :name="item.label"
              :value="item.value"
            ></TabsItem>
          </Tabs>
        </view>
        <view class="disFlx px-15 pb-8" v-if="currentTab === TabsListValueEnum.APLIST">
          <view
            v-for="item in statusList"
            :key="item.value"
            class="linh-30 operationBtn"
            @click.stop="statusChange(item.value)"
            :class="{ active: currentStatus === item.value }"
          >
            {{ item.label }}
          </view>
        </view>
        <view class="disFlx px-15 pb-8" v-if="currentTab === TabsListValueEnum.QUICK_APLIST">
          <view
            v-for="item in invitationStatusList"
            :key="item.value"
            class="linh-30 operationBtn"
            @click.stop="invitationStatusChange(item.value)"
            :class="{ active: invitationCurStatus === item.value }"
          >
            {{ item.label }}
          </view>
        </view>

        <view class="disFlx px-15 pb-8" v-if="currentTab === TabsListValueEnum.COOPERATE">
          <view
            v-for="item in noCooperationStatusList"
            :key="item.value"
            class="linh-30 operationBtn"
            @click.stop="noCooperationStatusChange(item.value)"
            :class="{ active: noCooperationCurStatus === item.value }"
          >
            {{ item.label }}
          </view>
        </view>
        <!-- <view class="pt-15 pb-6 px-15">
        <UniSearchBar v-if="currentTab === 3" placeholder="请输入机构名称搜索" @confirm="searchFnc" @cancel="restFnc"
          @clear="restFnc" />
      </view> -->
      </view>

      <Paglist
        v-model="dataList"
        :is-init-api="false"
        @register="register"
        :scroll-top-bottom="260"
        :is-show-loadmore="dataList.length > 1"
      >
        <template v-for="(item, index) in dataList" :key="item.tenantId + '-' + index">
          <view class="mx-15 forCard">
            <Association show-desc :limit="2" :info="item">
              <template #status>
                <template
                  v-if="
                    currentTab === TabsListValueEnum.APLIST ||
                    currentTab === TabsListValueEnum.QUICK_APLIST
                  "
                >
                  <view
                    v-if="item.apStatus === AuditStatusEnum.UNREVIEWED"
                    class="titleStatus ml-10 color1"
                  >
                    待审核
                  </view>
                  <view
                    v-if="item.apStatus === AuditStatusEnum.REJECT"
                    class="titleStatus ml-10 color3"
                  >
                    已驳回
                  </view>
                  <view
                    v-if="item.apStatus === AuditStatusEnum.CLOSE"
                    class="titleStatus ml-10 color3"
                  >
                    已取消
                  </view>
                  <view
                    v-if="item.apStatus === AuditStatusEnum.PASSED"
                    class="titleStatus ml-10 color2"
                  >
                    已通过
                  </view>
                </template>
                <view
                  v-if="currentTab === TabsListValueEnum.UNAPLIST && item.coope"
                  class="titleStatus ml-10 color2"
                >
                  已合作
                </view>
              </template>
            </Association>

            <view
              v-if="currentTab === TabsListValueEnum.APLIST"
              class="linh-25 mx-14 py-8 borderTop"
            >
              <view>合作项目：{{ item.projectName ?? '' }}</view>
              <view>
                合作方式：{{
                  item.cooperationType === CooperationTypeEnum.PUSH ? '资源推送' : '资源接入'
                }}
              </view>
              <view class="disFlxJS">
                <view>申请时间：{{ item.createTime }}</view>
                <view class="color1" @click.stop="goDetails(item)">查看详情></view>
              </view>
            </view>

            <view
              v-if="currentTab === TabsListValueEnum.QUICK_APLIST"
              class="linh-25 mx-14 py-8 borderTop"
            >
              <view class="disFlxJS">
                <view>申请时间：{{ item.createTime }}</view>
                <view class="color1" @click.stop="goInvitationDetail(item)">查看详情></view>
              </view>
            </view>

            <view
              v-else-if="currentTab === TabsListValueEnum.COOPERATE"
              class="disFlxJS linh-44 mx-15 borderTop"
            >
              <view v-if="!noCooperationCurStatus">
                已合作
                <text class="color1">{{ item.pronum }}</text>
                项资源
              </view>
              <view v-else></view>
              <view class="color1" @click.stop="goApplyCooperation(item)">查看详情></view>
            </view>

            <view
              v-else-if="currentTab === TabsListValueEnum.UNAPLIST"
              class="disFlxJS linh-44 mx-15 borderTop"
            >
              <view>
                <!-- 已合作
              <text class="color1">{{ item.cooperated }}</text>
              家, 共
              <text class="color1">{{ item.pronum }}</text>
              项资源 -->
              </view>
              <view class="color1" @click.stop="goApplyCooperation(item)">申请合作></view>
            </view>
          </view>
        </template>
      </Paglist>

      <ShowModal title="合作码" v-model="visible" :show-cancel="false">
        <template #content>
          <!-- <TRichText :content="quotaData.buyText" /> -->
          <view class="mt-15" style="color: #333; font-size: 28rpx">
            <text>请让合作方打开自己组织的小程序，在</text>
            <text style="font-weight: bolder">【个人中心】</text>
            <text>打开</text>
            <text style="font-weight: bolder">【扫一扫】</text>
            <text>扫码合作</text>
          </view>
          <view>
            <TImage
              :src="quotaQrCode"
              width="400rpx"
              height="400rpx"
              :show-menu-by-longpress="false"
            />
          </view>
        </template>
      </ShowModal>
    </view>
    <view style="position: absolute; left: -2000px; bottom: 0">
      <l-painter
        css="width: 240rpx; height: 240rpx;"
        style="background-color: #fff; text-align: center"
        isCanvasToTempFilePath
        @success="handlePainterSuccess"
      >
        <l-painter-qrcode
          :text="quotaData.qrCode"
          css="width: 200rpx; height: 200rpx; margin: 0 auto; margin-top: 20rpx"
        />
      </l-painter>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  CooperationList  合作管理 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import TImage from '@/components/TImage/index.vue';
  import Tabs from '@/components/tabs/index.vue';
  import TabsItem from '@/components/tabs/item.vue';
  import TabNav from '@/components/tabs/nav.vue';
  import ShowModal from '@/components/ShowModal/index.vue';

  import { ref, unref, watch, provide } from 'vue';
  import Association from '../components/association.vue';
  import Paglist from '@/components/Paglist/index.vue';
  import { useConList } from '@/components/Paglist/useConList';
  import {
    cooperationQuota,
    getApList,
    getCooperatedList,
    getCooperationInvitationList,
    getMarketList,
    getNoCooperationPage,
  } from '@/api/cooperation';
  import { type QuotaData } from '@/api/cooperation/types';
  import { TabsListValueEnum, CooperationTypeEnum, AuditStatusEnum } from '@/enums/cooperationEnum';
  import { type AssociationCard } from '@/api/cooperation/types';
  import { navigateTo } from '@/router';
  import { onPageScroll, onShareAppMessage, onShow } from '@dcloudio/uni-app';
  import { useAppStoreWithOut } from '@/store/modules/app';
  import lPainter from '@/uni_modules/lime-painter/components/l-painter/l-painter.vue';
  import lPainterQrcode from '@/uni_modules/lime-painter/components/l-painter-qrcode/l-painter-qrcode.vue';
  import { encrypt } from '@/utils/CryptoJS';
  import { useUserStoreWithOut } from '@/store/modules/user';
  import { useAppShare } from '@/hooks/core/useAppShare';

  const { setWxSharePath } = useAppShare();
  const { userInfo } = useUserStoreWithOut();
  const { globalConfig } = useAppStoreWithOut();
  const visible = ref(false);

  // 获取头部权益数量信息
  const quotaData = ref<QuotaData>({
    quota: 0,
    product: '',
    usable: 0,
    cooperated: 0,
    endtime: '',
    buyText: '',
    qrCode: '',
  });
  function getQuota() {
    cooperationQuota().then((res) => {
      quotaData.value = res;
    });
  }

  const quotaQrCode = ref('');
  function handlePainterSuccess(url: string) {
    quotaQrCode.value = url;
  }

  onShow(async () => {
    getQuota();
    refresh && refresh();
  });

  // 查询协会列表
  const [register, { refresh }] = useConList();
  const currentTab = ref(TabsListValueEnum.QUICK_APLIST);

  const dataList = ref<AssociationCard[]>([]); //协会列表

  provide('api', (obj: any) => {
    if (unref(currentTab) === TabsListValueEnum.APLIST) {
      return getApList({ ...obj, isCreate: unref(currentStatus) });
    }
    if (unref(currentTab) === TabsListValueEnum.COOPERATE) {
      if (noCooperationCurStatus.value) {
        return getNoCooperationPage(obj);
      } else {
        return getCooperatedList(obj);
      }
    }
    if (unref(currentTab) === TabsListValueEnum.UNAPLIST) {
      return getMarketList(obj);
    }
    if (unref(currentTab) === TabsListValueEnum.QUICK_APLIST) {
      return getCooperationInvitationList({ ...obj, isCreate: unref(invitationCurStatus) });
    }
  });

  // 监听tab切换
  watch(currentTab, tabsChange);
  function tabsChange(index: number) {
    currentTab.value = index;
    refresh && refresh();
  }

  // 列表头部tabs
  const tabItemList = ref([
    {
      label: '已合作资源',
      value: TabsListValueEnum.COOPERATE,
    },
    // {
    //   label: '可合作资源',
    //   value: TabsListValueEnum.UNAPLIST,
    // },
    {
      label: '资源申请',
      value: TabsListValueEnum.APLIST,
    },
    {
      label: '组织申请',
      value: TabsListValueEnum.QUICK_APLIST,
    },
  ]);
  const currentStatus = ref(CooperationTypeEnum.INSERT);
  const statusList = ref([
    {
      label: '我发起的',
      value: CooperationTypeEnum.INSERT,
    },
    {
      label: '向我申请的',
      value: CooperationTypeEnum.PUSH,
    },
  ]);
  function statusChange(val: number) {
    currentStatus.value = val;
    refresh && refresh();
  }

  const invitationCurStatus = ref(CooperationTypeEnum.INSERT);
  const invitationStatusList = ref([
    {
      label: '我发起的',
      value: CooperationTypeEnum.INSERT,
    },
    {
      label: '我收到的',
      value: CooperationTypeEnum.PUSH,
    },
  ]);
  function invitationStatusChange(val: number) {
    invitationCurStatus.value = val;
    refresh && refresh();
  }

  const noCooperationCurStatus = ref(0);
  const noCooperationStatusList = ref([
    {
      label: '已有合作项目',
      value: 0,
    },
    {
      label: '暂无合作项目',
      value: 1,
    },
  ]);
  function noCooperationStatusChange(val: number) {
    noCooperationCurStatus.value = val;
    refresh && refresh();
  }

  const headerHeight = ref(0);
  // 跳转合作说明
  const goDescription = function () {
    navigateTo({ name: 'equityExplain' });
  };
  // 申请记录 - 申请合作详情
  const goDetails = function (item: AssociationCard) {
    uni.setStorageSync('_CLICK_INFO', item);
    navigateTo({
      name: 'cooperationDetails',
      options: { id: item.id as number, type: currentTab.value },
    });
  };

  function goInvitationDetail(item: AssociationCard) {
    navigateTo({
      name: 'cooperationInvitationDetail',
      options: { id: item.id as number, type: currentTab.value },
    });
  }

  // 合作单位,合作资源 - 合作详情
  const goApplyCooperation = async function (item: AssociationCard) {
    // await isSetPlay(item.tenantId); // 判断是否开通支付
    uni.setStorageSync('_CLICK_INFO', item);
    navigateTo({ name: 'applyCooperation' });
  };

  onShareAppMessage(() => {
    return {
      title: '诚邀您共建社会组织网络生态',
      path: setWxSharePath({
        name: 'inviteCooperation',
        options: { key: encrypt(userInfo.mainUserId.toString()) },
      }),
      imageUrl:
        'https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saasHome/20231207-150350.jpg',
    };
  });

  onPageScroll(() => {});

  // const orgName = ref('') // 合作资源查询条件
  // const listTotal = ref(0)

  // 合作资源搜索
  // function searchFnc(e: { value: string }) {
  //   orgName.value = e.value;
  //   refresh && refresh();
  // }
  // 合作资源搜索重置
  // function restFnc() {
  //   orgName.value && searchFnc({ value: '' });
  // }
</script>

<style lang="scss" scoped>
  $color-primary: #2878ff;
  $text-red: #ff6b6b;
  $text-color: #aaabab;

  .color1 {
    color: $color-primary;
  }

  .color2 {
    color: $text-red;
  }

  .color3 {
    color: $text-color;
  }

  .container {
    font-size: 28rpx;
  }

  .headCard {
    // margin: 30rpx 30rpx 10rpx 30rpx;
    background-color: #ffffff;
    // border-radius: 20rpx;

    .rightBox {
      display: flex;
      justify-content: space-between;
      width: 100%;
    }
  }

  .stickyTabs {
    position: sticky;
    z-index: 99;

    .operationBtn {
      background-color: #d0f7ff;
      color: #2878ff;
      padding: 0 20rpx;
      text-align: center;
      flex-shrink: 0;
      border-radius: 10rpx;
      position: relative;
    }

    .operationBtn + .operationBtn {
      margin-left: 30rpx;
    }

    .operationBtn.active {
      background-color: #2878ff;
      color: #ffffff;
    }
  }

  .shopBtn {
    position: relative;
    color: $color-primary;
    border: solid 1px $color-primary;
    border-radius: 10rpx;
    width: 124rpx;
    text-align: center;
    height: 40rpx;
    line-height: 40rpx;
    font-size: 24rpx;
    flex-shrink: 0;
    .share-btn {
      width: 100%;
      height: 100%;
      position: absolute;
      left: 0;
      top: 0;
      opacity: 0;
    }
  }

  .forCard {
    background-color: #ffffff;
    box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.15);
    border-radius: 20rpx;
    overflow: hidden;
    margin-top: 10rpx;

    .titleStatus {
      font-size: 24rpx;
      width: 124rpx;
      text-align: center;
      height: 40rpx;
      line-height: 40rpx;
      flex-shrink: 0;
      border-radius: 10rpx;
    }

    .titleStatus.color1 {
      color: #458aff;
    }

    .titleStatus.color2 {
      color: #ffa944;
    }

    .titleStatus.color3 {
      color: #ff4a4a;
    }
  }

  .forCard + .forCard {
    margin-top: 30rpx;
  }

  .borderTop {
    border-top: 1px solid #dddddd;
  }
</style>
